<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div id="userLayout" :class="['user-layout-wrapper']">
    <div class="container">
      <div class="container_box">
        <div class="login_content">
          <div class="logo">
            <img src="~@/assets/img/login-logo.png" alt="logo" />
          </div>
        </div>
        <div class="login-banner">
          <h2>推进核心能力平台共建共享</h2>
          <em>Promote the co-construction and sharing of core capability platforms</em>
        </div>
      </div>
      <div class="footer">
        <div class="copyright">&copy; {{ loginConfig.copyright }}</div>
      </div>
      <ChangePassword v-if="showChangePwd" :user-info="modelRef" @close="showChangePwd = false" />
      <LicenseUpload v-if="showUploadModal" @close="showUploadModal = false" />
    </div>
    <div class="login_box">
      <div class="login_box_inner">
        <img src="~@/assets/img/rightLogo.svg" />
        <!-- <h2>DevCenter</h2> -->
        <h1>
          <span>{{ loginConfig.title }}{{ loginConfig.subTitle }}</span>
          <span class="tag-box">
            <img v-if="loginConfig.secretLevel == '公开'" src="~@/assets/img/mj-gk.svg" />
            <img v-if="loginConfig.secretLevel == '内部'" src="~@/assets/img/mj-nb.svg" />
            <img v-if="loginConfig.secretLevel == '受控'" src="~@/assets/img/mj-sk.svg" />
            <img v-if="loginConfig.secretLevel == '普通商密'" src="~@/assets/img/mj-ptsm.svg" />
            <img v-if="loginConfig.secretLevel == '核心商密'" src="~@/assets/img/mj-hxsm.svg" />
            <img v-if="loginConfig.secretLevel == '秘密'" src="~@/assets/img/mj-mm.svg" />
            <img v-if="loginConfig.secretLevel == '机密'" src="~@/assets/img/mj-jm.svg" />
          </span>
        </h1>

        <div class="main">
          <a-form id="formLogin" layout="vertical" class="user-layout-login">
            <a-form-item v-bind="validateInfos.username">
              <h4>用户名</h4>
              <a-input v-model:value="modelRef.username" size="large" placeholder="请输入用户名" style="width: 100%">
                <template #prefix>
                  <AvicIcon svg="user-outlined" avic-icon-class="prefixIcon" />
                </template>
              </a-input>
            </a-form-item>

            <a-form-item v-bind="validateInfos.password">
              <h4>密码</h4>
              <a-input-password v-model:value="modelRef.password" size="large" placeholder="请输入密码">
                <template #prefix>
                  <AvicIcon svg="lock-outlined" avic-icon-class="prefixIcon" />
                </template>
              </a-input-password>
            </a-form-item>

            <!-- <a-form-item>
                    <a-checkbox v-model:checked="modelRef.rememberMe">记住用户名</a-checkbox>
                  </a-form-item> -->

            <a-form-item style="margin-top: 24px; margin-bottom: 16px">
              <a-button
                size="large"
                type="primary"
                block
                html-type="submit"
                class="login-button"
                :loading="state.loginBtn"
                @click="(e) => handleSubmit(e, { force: undefined })"
              >
                登 录
              </a-button>
              <!-- <p style="color: #909399; text-align: center; margin: 0">技术支持：{{ loginConfig.phone }}</p> -->
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import type { ResponseBaseData } from '@/api/model/baseModel';
import { encrypt } from '@/utils/common-util';
import { Form } from 'ant-design-vue';
import { useRoute, useRouter } from 'vue-router';
import type { RequestError } from '@/utils/request';
import { useUserStore } from '@/store/user';
import { getLincenseIsAdmin } from '@/api/user/login';
import ChangePassword from './ChangePassword.vue';
import LicenseUpload from './LicenseUpload.vue';
import store from '@/utils/local-storage';
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const { loginConfig } = window.$config;
const state = reactive({
  loginBtn: false
});
const modelRef = reactive({
  rememberMe: true,
  username: '',
  password: ''
});
const { validate, validateInfos } = Form.useForm(
  modelRef,
  reactive({
    username: [{ required: true, message: '请输入用户名', type: 'string' }],
    password: [{ required: true, message: '请输入密码', type: 'string', trigger: ['blur', 'change'] }]
  })
);
onMounted(() => {
  modelRef.username = store.get('REMEMBER_ME') || '';
  if (proxy.$settings?.defaultUserInfo?.username) {
    modelRef.username = proxy.$settings?.defaultUserInfo?.username ?? '';
    modelRef.password = proxy.$settings?.defaultUserInfo?.password ?? '';
  }
});
const showChangePwd = ref(false);
const showUploadModal = ref(false);
const requestFailed = (err: RequestError) => {
  if (err.code && err.code === '903') {
    showChangePwd.value = true;
    return;
  }
  if (err.code && err.code === '911') {
    // 校验用户是否有权限上传授权文件
    const reqParams = { username: modelRef.username };
    getLincenseIsAdmin(reqParams).then((res: any) => {
      if (res.data) {
        // 打开上传平台授权文件页面
        showUploadModal.value = true;
      } else {
        proxy.$message.warning(res.message);
      }
    });
  } else if (err.code && err.code === '904') {
    // 限制用户多终端登录
    // 给出提示：是否踢出已登录终端
    proxy.$confirm({
      title: '是否踢出已登录终端？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        // 确定踢出，带着踢出的参数重新调登录接口
        handleSubmit(null, { force: true });
      },
      onCancel: () => {
        // 取消踢出，不进行登录
      }
    });
  }
};
const handleSubmit = (e: Event, { force }) => {
  if (e) {
    e.preventDefault();
  }
  const validateNames = ['username', 'password'];
  state.loginBtn = true;
  validate(validateNames)
    .then((values) => {
      values.password = encrypt(values.password);
      const loginParams = Object.assign(values, {
        force
      });
      userStore
        .LOGIN(loginParams)
        .then((res: ResponseBaseData<any>) => {
          if (modelRef.rememberMe) {
            store.set('REMEMBER_ME', values.username);
          } else {
            store.set('REMEMBER_ME', '');
          }
          const loginUser = res.data.userInfo;
          const { consoleType } = loginUser;
          // 重定向优先级 redirectUrl > 后台用户
          if (route.query?.redirect_url) {
            window.name = 'portal';
            router.push(decodeURIComponent((route.query?.redirect_url as string) || '') || '/');
          } else if (consoleType === '0' && proxy.$settings.consoleUrl) {
            let { consoleUrl } = proxy.$settings;
            consoleUrl = consoleUrl.endsWith('/') ? consoleUrl : `${consoleUrl}/`;
            window.name = 'console';
            window.open(`${consoleUrl}access-from-portal?access_token=${res.data.token}&redirect_url=/backstage`, 'console');
          } else {
            window.name = 'portal';
            router.push('/');
          }
        })
        .catch((err) => {
          requestFailed(err);
        })
        .finally(() => {
          state.loginBtn = false;
        });
    })
    .catch((/* err */) => {
      // 屏蔽错误处理
      // requestFailed(err);
      state.loginBtn = false;
    });
};
</script>

<style lang="less" scoped>
.user-layout-login :deep(.ant-tabs) {
  .ant-tabs-nav::before {
    border-bottom: none;
  }
}

#userLayout.user-layout-wrapper {
  height: 100%;
  display: flex;
  justify-content: space-between;

  .container {
    position: relative;
    width: calc(100% - 30%);
    min-height: 100%;
    background: url('~@/assets/img/login-wrapper.png') no-repeat left bottom;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .container_box {
      height: 100%;
    }
    .logo {
      color: #fff;
      display: flex;
      align-items: center;
      margin-bottom: 44px;

      & > svg,
      & > img {
        width: 348px;
        height: 53px;
      }
      > span {
        font-size: 32px;
        font-family: 'Alibaba-PuHuiTi-Bold';
      }

      .tag-box {
        display: inline-flex;
        margin-top: -20px;
        margin-left: 6px;
        // span {
        //   font-size: 14px;
        //   padding: 0 8px;
        //   border-radius: 12px;
        //   display: inline-block;
        //   text-align: center;
        //   font-weight: normal;
        //   margin-bottom: 14px;
        //   margin-left: 8px;
        // }
      }
    }
    :deep(.ant-input):focus,
    .ant-input-focused {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px #ddefff;
    }

    :deep(.ant-input-affix-wrapper):focus,
    .ant-input-affix-wrapper-focused {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px #ddefff;
    }
    :deep(.ant-input):hover,
    .ant-input-affix-wrapper:hover {
      border-color: #7fc1ff;
    }
    :deep(.ant-input-affix-wrapper):not(.ant-input-affix-wrapper-disabled):hover {
      border-color: #7fc1ff;
    }
    button.login-button {
      width: 100%;
      background: #1890ff;
      border-color: #1890ff;
      margin-top: 8px;
      margin-bottom: 32px;
    }

    .login_content {
      position: absolute;
      top: 40px;
      left: 65px;
      h4 {
        color: #606266;
      }
    }
    .login-banner {
      width: 100%;
      height: 100%;
      display: flex;
      padding: 150px 0 60px;
      align-items: center;
      justify-content: start;
      flex-direction: column;
      font-weight: normal;
      text-shadow: 0px 2px 6px rgba(0, 0, 0, 0.6);

      & > h2 {
        color: #ffffff;
        font-size: 48px;
        line-height: 56px;
        text-align: center;
        margin-bottom: 12px;
        margin-top: 12%;
        font-weight: 600;
        letter-spacing: 3px;
      }
      & > em {
        color: #ffffff;
        font-size: 16px;
        font-style: normal;
        line-height: 24px;
        letter-spacing: 0.075em;
      }
    }
    .footer {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      margin: 12px;
      color: rgba(255, 255, 255, 0.8);
      text-align: center;

      .copyright {
        font-size: 14px;
        text-align: center;
        line-height: 22px;
      }
    }
  }
  .login_box {
    width: 30%;
    max-width: 520px;
    min-width: 480px;
    background-color: #fff;
    border-radius: 8px;
    // padding: 0 100px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    h1 {
      color: #1d2129;
      font-size: 32px;
      font-family: 'Alibaba-PuHuiTi-Bold';
      display: flex;
      .tag-box {
        display: inline-flex;
        margin-top: 2px;
        margin-left: 6px;
        height: 18px;
      }
    }
    h2 {
      color: #0061c5;
      font-size: 28px;
      letter-spacing: 1px;
      font-weight: 600;

      em {
        color: #0061c5;
        font-weight: bold;
        font-style: normal;
      }
      // .initial {
      //   font-weight: 600;
      // }
    }
    .ant-input-affix-wrapper-lg,
    .ant-input-lg {
      height: 40px;
      line-height: 40px;
      padding: 4px 8px;
    }
    .login_box_inner {
      width: 420px;
      margin: -100px auto 0;
      h1 {
        margin: 12px 0 108px 0;
        font-family: 'Alibaba-PuHuiTi-Bold';
        font-size: 28px;
        color: #1d2129;
        line-height: 40px;
      }
    }
  }
}
</style>
